package com.ruoyi.job.util;

import javax.mail.*;
import javax.mail.internet.*;
import java.util.Properties;

public class EmailUtils {

    // 邮件服务器配置
    private static final String SMTP_HOST = "smtp.qq.com";
    private static final int SMTP_PORT = 587;
    private static final String USERNAME = "792572942@qq.com"; // 发件邮箱
    private static final String PASSWORD = "pyidtmgfyfdnbbcj";   // SMTP授权码
    private static final String TOMAIL = "792572942@qq.com";    // 收件邮箱

    /**
     * 发送邮件到指定邮箱
     *
     * @param subject 邮件主题
     * @param content 邮件内容
     * @throws MessagingException 邮件发送异常
     */
    public static void sendEmail(String subject, String content)
            throws MessagingException {

        // 1. 配置邮件服务器属性
        Properties props = new Properties();
        props.put("mail.smtp.host", SMTP_HOST);
        props.put("mail.smtp.port", SMTP_PORT);
        props.put("mail.smtp.auth", "true");
        props.put("mail.smtp.starttls.enable", "true");

        // 2. 创建认证会话
        Session session = Session.getInstance(props, new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(USERNAME, PASSWORD);
            }
        });

        try {
            // 3. 创建邮件消息
            Message message = new MimeMessage(session);
            message.setFrom(new InternetAddress(USERNAME));
            message.setRecipient(Message.RecipientType.TO, new InternetAddress(TOMAIL));
            message.setSubject(subject);

            // 4. 设置邮件内容（支持HTML格式）
            message.setContent(content, "text/html;charset=UTF-8");

            // 5. 发送邮件
            Transport.send(message);
            System.out.println("邮件发送成功至: " + TOMAIL);
        } catch (AddressException e) {
            throw new MessagingException("邮箱地址格式错误", e);
        }
    }
}